package com.lzq.mq.common.coder;

import com.lzq.mq.common.constants.TcpConstants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class TcpMsgEncoder extends MessageToByteEncoder {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {

        TcpMsg tcpMsg = (TcpMsg) o;     // 强转对象获取消息对象
        // 封装消息
        byteBuf.writeShort(TcpMsg.magic);
        byteBuf.writeInt(tcpMsg.getCode());
        byteBuf.writeInt(tcpMsg.getLen());
        byteBuf.writeBytes(tcpMsg.getBody());
        byteBuf.writeBytes(TcpConstants.DEFAULT_DECODE_CHAR.getBytes());    // 防止粘包
    }
}
